<%+header%>

<style>
.realsync-log {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 15px;
    font-family: monospace;
    font-size: 12px;
    line-height: 1.4;
    max-height: 400px;
    overflow-y: auto;
    white-space: pre-wrap;
    word-wrap: break-word;
    color: #333;
}

.log-line {
    margin: 0;
    padding: 1px 0;
}

.log-line.error {
    color: #dc3545;
}

.log-line.warning {
    color: #ffc107;
}

.log-line.info {
    color: #17a2b8;
}

.log-line.debug {
    color: #6c757d;
}
</style>

<div class="realsync-log">
<% 
local log_content = ""
if nixio.fs.access("/var/log/realsync.log") then
    log_content = luci.sys.exec("tail -n 100 /var/log/realsync.log 2>/dev/null")
end

if log_content and log_content ~= "" then
    for line in log_content:gmatch("[^\r\n]+") do
        local css_class = ""
        if line:match("ERROR") or line:match("error") then
            css_class = "error"
        elseif line:match("WARN") or line:match("warning") then
            css_class = "warning"
        elseif line:match("INFO") or line:match("info") then
            css_class = "info"
        elseif line:match("DEBUG") or line:match("debug") then
            css_class = "debug"
        end
%>
    <div class="log-line <%=css_class%>"><%=line%></div>
<%
    end
else
%>
    <div class="log-line">暂无日志内容</div>
<%
end
%>
</div>

<button id="clearlog" class="cbi-button cbi-button-reset" style="margin-left:10px;">清空日志</button>
<button id="refreshlog" class="cbi-button">刷新日志</button>
<pre id="logcontent">...</pre>

<%+footer%>

<script>
document.getElementById('clearlog').onclick = function() {
    XHR.get('/cgi-bin/luci/admin/services/realsync/clearlog', null, function() {
        alert('日志已清空');
        location.reload();
    });
};

function fetchLog() {
    XHR.get('/cgi-bin/luci/admin/services/realsync/get_log', null, function(x, data) {
        if (data && data.log) {
            document.getElementById('logcontent').textContent = data.log;
        }
    });
}

document.getElementById('refreshlog').onclick = function() {
    fetchLog();
};

setInterval(fetchLog, 1000);

fetchLog();
</script>
